package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.task.WebSocketTask;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocketTask.WebSocketServer;
import io.swagger.util.Json;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    WebSocketServer webSocketServer;


    /**
     * 提交订单
     * @param dto
     * @return
     */
    @Override
    public Result submitOrder(OrdersSubmitDTO dto) {
        //判断地址是否为空,通过id查询地址是否为空
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null){
            //地址为空不能下单直接返回
            return Result.error(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //判断购物车是否为空,根据userId查询购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(BaseContext.getCurrentId());
        if (shoppingCartList == null && shoppingCartList.size()==0){
            //购物车数据为空不能下单
            return Result.error(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //插入订单表,购物车和地址都不为空可以插入数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto , orders);
        //补全数据
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//这里直接用毫秒值转换成String作为订单号
        //订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //下单用户id
        orders.setUserId(BaseContext.getCurrentId());
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //手机号
        orders.setPhone(addressBook.getPhone());
        //地址
        orders.setAddress(addressBook.getDetail());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //配送状态
        orders.setDeliveryStatus(1);
        //插入
        orderMapper.insert(orders);


        //批量插入订单明细表,明细表里可能有菜品和套餐,插入的数据可能不止一条所以要批量插入
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //补充订单id orderMapper.insert(orders);这里返回的
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insert(orderDetailList);

        //清空购物车
        shoppingCartMapper.clean(BaseContext.getCurrentId());


        //返回数据
        OrderSubmitVO vo = OrderSubmitVO
                .builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return Result.success(vo);
    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }


    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 用户催单
     * @param id
     * @return
     */
    @Override
    public Result reminder(Long id) {
        //参数处理
        if (id == null){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }

        //查询订单
        Orders orders = orderMapper.getById(id);
        //判空
        if (orders == null){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }

        //发送催单警告到商家客户端
        /*
        type 为消息类型，1为来单提醒 2为客户催单
        orderId 为订单id
        content 为消息内容
        这里用map来封装,并装换为json字符串发送给商家客服端
         */
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+orders.getNumber());
        String message = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(message);

        return Result.success();
    }

}
